package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @title: LoginService
 * @Author TGE
 * @Date: 2021/5/9 12:21
 * @Version 1.0
 */
@Slf4j
@Service
public class LoginService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    /**
     * 验证码校验
     * @param pram
     * @return
     */
    public Map<String, Boolean> login(Map<String, String> pram) {
        String phone = pram.get("phone");
        String verificationCode = pram.get("verificationCode");
        String redisCode ="CHECK_CODE_"+phone;
        Boolean isNew = false;
        String  code = (String) redisTemplate.opsForValue().get(redisCode);
        Object o = redisTemplate.boundValueOps(redisCode).get();
        //验证码错误
        if (!o.equals(verificationCode)){
            return null;
        }
        //验证码正确删除Redis中的key
        redisTemplate.delete(redisCode);

        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("mobile",phone);
        //数据库查询是否存在 不存在注册新用户
        User user = userMapper.selectOne(queryWrapper);
        if (null==user){
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            isNew = true;
        }

        //生成token
        Map<String, Object> header = new HashMap<String, Object>();
        header.put(JwsHeader.TYPE, JwsHeader.JWT_TYPE);
        header.put(JwsHeader.ALGORITHM, "HS256");

        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("mobile", user.getMobile());
        claims.put("id", user.getId());

        // 生成token
        String jwt = Jwts.builder()
                .setHeader(header)  //header，可省略
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new Date(System.currentTimeMillis() + 1000*60*60*12)) //设置过期时间，3秒后过期
                .compact();

        try {
            //发送用户登录成功的消息
            Map<String,Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("date", System.currentTimeMillis());

            rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
            log.error("发送消息失败！", e);
        }


        Map result = new HashMap<String, Boolean>();
        result.put("token",jwt);
        result.put("isNew",isNew);
        return result;
    }
}
